package hn.sigit.view.topography;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.context.FacesContext;

import hn.sigit.dao.hnd.cadastre.HND_SpatialZoneDAO;
import hn.sigit.dao.hnd.special.HND_CounterDAO;
import hn.sigit.logic.geometry.GeometryOperations;
import hn.sigit.model.commons.IParcel;
import hn.sigit.model.commons.ISpatialZone;
import hn.sigit.model.hnd.cadastre.HND_Parcel;
import hn.sigit.model.hnd.cadastre.HND_SpatialZone;
import hn.sigit.model.hnd.special.HND_CounterType;

import org.geotools.geometry.jts.WKTReader2;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryCollection;
import com.vividsolutions.jts.io.ParseException;

@Name("topographyMaintenanceHelper")
@Scope(value=ScopeType.CONVERSATION)
@AutoCreate
public class TopographyMaintenanceHelper {
	private String zoneWkts;
	

	public String getZoneWkts() {
		return zoneWkts;
	}
	public void setZoneWkts(String zoneWkts) {
		this.zoneWkts = zoneWkts.trim();
	}


	public void saveZones() {
		if (zoneWkts == null || zoneWkts.trim().equals("")) return;
		
		ISpatialZone newSpatialZone;
		Geometry geom;
		GeometryCollection geomCollection;
		
		WKTReader2 wktReader = new WKTReader2(GeometryOperations.geomFactory);
		try {
			geom = wktReader.read(zoneWkts);
		}
		catch (ParseException pe) {
			pe.printStackTrace();
			return;
		}
		
		if ( !(geom instanceof GeometryCollection) ) return;
		
		geomCollection = (GeometryCollection) geom;
		
		//Validate that every geometry is simple and valid
		for (int i = 0; i < geomCollection.getNumGeometries(); i++) {
			geom = geomCollection.getGeometryN(i);
			
			if (!geom.isSimple() || !geom.isValid()) {
				FacesContext.getCurrentInstance().addMessage(
						"",
						new FacesMessage(
								FacesMessage.SEVERITY_ERROR,
								"ERROR: Uno o mas elementos geometricos no son validos",
								""
						)
				);
				return;
			}
		}
		
		//Store each geometry in its corresponding layer
		for (int i = 0; i < geomCollection.getNumGeometries(); i++) {
			geom = geomCollection.getGeometryN(i);
			//TODO: we might also want to instantiate HND_SpatialZone depending
			//on the current layer.
			newSpatialZone = new HND_Parcel();
			newSpatialZone.setShape(geom);
			if (newSpatialZone instanceof IParcel)
				((IParcel) newSpatialZone).setFieldTab(new Long(HND_CounterDAO.nextValue(HND_CounterType.FIELD_TAB)));
			
			//TODO: Create the corresponding Property
			//TODO: Set the proper layer
			
			HND_SpatialZoneDAO.save(newSpatialZone);
		}
	}
	public void cancel() {
		setZoneWkts(null);
	}
}
